import { WebUSB } from "usb";
import { MicrobitWebUSBConnection } from "../src/device/webusb";
import { DefaultHost } from "../src/fs/host";
import { FileSystem, VersionAction } from "../src/fs/fs";
import { fsMicroPythonSource } from "../src/utils";
import { readWorkspaceFiles } from './util';

const logging = {
  event: console.log,
  error: console.log,
  log: console.log,
};


/**
 * flash default demo file
 */
async function flashDefault() {
  const customWebUSB = new WebUSB({
    devicesFound: async (devices) =>
      devices.find((device) => device.vendorId === 0x0d28),
  });
  const connection = new MicrobitWebUSBConnection({ logging });
  connection.getOneAvailableDevice = async () => {
    const device = await customWebUSB.requestDevice({
      filters: [],
    });
    return device;
  };
  await connection.connect();
  const host = new DefaultHost();
  const ufs = new FileSystem(logging, host, fsMicroPythonSource);
  ufs.write(
    "main.py",
    `# Imports go at the top
from microbit import *


# Code in a 'while True:' loop repeats forever
while True:
    print(1)
    display.show(Image.HEART)
    sleep(1000)
    display.scroll('111')
`,
    VersionAction.MAINTAIN
  );
  await connection.flash(ufs, {
    partial: true,
    progress: (a) => {
      console.log(a);
    },
  });
}

/**
 * flash files in workspace
 */
export async function flashWorkspace(workspaceDir) {
  const customWebUSB = new WebUSB({
    devicesFound: async (devices) =>
      devices.find((device) => device.vendorId === 0x0d28),
  });
  const connection = new MicrobitWebUSBConnection({ logging });
  connection.getOneAvailableDevice = async () => {
    const device = await customWebUSB.requestDevice({
      filters: [],
    });
    return device;
  };
  await connection.connect();
  const host = new DefaultHost();
  const ufs = new FileSystem(logging, host, fsMicroPythonSource);

  const modules = readWorkspaceFiles(workspaceDir);
  for(const module of modules) {
    ufs.write(module.filename, module.content, VersionAction.MAINTAIN);
  }
  await connection.flash(ufs, {
    partial: true,
    progress: (a) => {
      console.log(a);
    },
  });
}